<template>
  <div>
    <el-row>
      <el-col :span="24" align="right">
<!--        <el-button type="primary" @click="addPeople()">添加单位</el-button>-->
      </el-col>
    </el-row>
    <Table :tableArr="unitList" :pagination="data.page" :columns="data.columns">
      <template #operate="{ row }">
<!--        <el-button size="small" class="ordinary" @click="handleEdit(row)">编辑</el-button>-->
<!--        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>-->
      </template>
    </Table>

    <el-dialog v-model="data.addPeople" append-to-body width="800px"  :show-close="false"
      :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="data.activeName" class="demo-tabs">
            <el-tab-pane label="添加单位" name="first">
              <el-form v-model="data.addPeople" append-to-body width="800px" label-width="110px" top="10vh"
                :show-close="false" :close-on-click-modal="false">
                <el-row :gutter="40">
                  <el-col :span="12">
                    <el-form-item label="单位类型：">
                      <SelectOption :selectValue="form.unitType" :options="data.unitSelet" @change-value="changeValue0">
                      </SelectOption>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="单位名称：">
                      <popup-tree-input v-if="form.unitTypeId == '0'" :data="data.popupTreeData"
                        :props="data.popupTreeProps" :prop="data.deptForm.parentName == null
                          ? $t('message.org.top_menu')
                          : form.unitName
                          " :node-key="'' + data.deptForm.parentId" :current-change-handle="changeValue7" />
                      <el-input type="text" v-model="form.unitName" @change="form.unitId = form.unitName"
                        v-else></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="40">
                  <el-col :span="12">
                    <el-form-item label="单位排名：">
                      <el-input-number v-model="form.sort" :step="1" style="width: 100%" :min="1"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系人：">
                      <el-input type="text" v-model="form.contactId" v-if="form.unitTypeId == '1'" placeholder="联系人"
                        maxlength="15"></el-input>
                      <!-- <SelectOption :selectValue="form.contact" :options="data.roleList" @change-value="changeValue2"
                        v-else></SelectOption> -->
                        <user-list-modal
                          v-model="form.contact"
                          @update:modelValue="changeValue2"
                          :default-users="[]"
                          :multiple="false"
                          :devType="'platform'"
                          v-else
                        />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="40">
                  <el-col :span="12">
                    <el-form-item label="联系方式：">
                      <el-input type="text" v-model="form.phone" :disabled="form.unitTypeId == '0'"
                        maxlength="11"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.addPeople = false">关闭</el-button>
          <el-button type="primary" @click="save()">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script >
import { validatePhoneNumber } from '@/utils/util'
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import common from "@/views/science/common/common.json";
import PopupTreeInput from "@/views/science/components/PopupTreeInput/index.vue";
import SelectOption from "@/views/science/components/selectOption/index.vue";
import Table from "@/views/science/components/table/table.vue";
import { Modals , tips} from '@/views/science/components/tips/tips';
import { getOrgTree } from "@/views/system/api/org";
import { onMounted, reactive, ref, watch } from "vue";
import UserListModal from '@/views/project/components/UserListModal/index.vue';

export default {
  components: {
    Table,
    SelectOption,
    PopupTreeInput,
    UserListModal,
  },
  emits: {
    dataChange: null,
    paramsChange: null,
  },
  props: {
    members: {
      type: Array,
      required: true,
    },
    membersFlag: {
      type: Boolean,
      required: true,
    },
  },
  setup(props, { emit }) {
    const value = ref([]);
    let data = reactive({
      activeName: ref("first"),
      columns: common.platformUnitInfoHeader,
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      addPeople: false,

      unitSelet: [
        { id: "0", name: "内部公司" },
        { id: "1", name: "外部公司" },
      ],

      usersSelet: [],
      roleList: [],
      popupTreeData: [], //单位名称
      popupTreeProps: {
        //单位名称
        label: "name",
        children: "children",
      },
      deptForm: {
        parentId: 0,
        parentName: "",
      },
      addType: "add", //add or edit
      editItem: {}, //当前编辑的人员
    });
    const unitList = reactive([]);
    const form = reactive({
      unitType: "",
      unitTypeId: "0", //单位类型
      unitName: "", //单位名称
      unitId: "", //单位名称
      sort: 1, //排名
      contact: "", //联系人
      contactId: "", //联系人
      phone: "", //联系方式
      id: new Date().getTime(),
    });

    // 字典
    const affiliation = async () => {
      request({
        url: proxy.CHECC_API_CMS + "/user/getAll",
        method: "get",
      }).then((res) => {
        data.roleList = res.data.data;
      });
      let res = await getOrgTree();
      data.popupTreeData = res.data.data;
    };

    const changeValue7 = (item) => {
      form.unitName = item.name;
      form.unitId = item.id;
    };

    const changeValue0 = async (item) => {
      form.unitTypeId = item.id;
      form.unitType = item.name;
      form.phone = ''
    };
    //联系人
    const changeValue2 = (item) => {
      form.contactId = item.userId;
      form.contact = item.cname;
      if (form.unitTypeId == "0") {
        form.phone = item.phone;
      } else {
        form.phone = "";
      }
    };
    //添加人员
    const addPeople = () => {
      data.addPeople = true;
      data.addType = "add";
    };
    //编辑人员
    const handleEdit = (row) => {
      console.log("编辑", row);

      Object.assign(form, row);


      data.addPeople = true;

      data.addType = "edit";

      data.editItem = row;

      console.log(row)

      if(row.unitTypeId=='0'){

        data.editItem = row;

      }else{

        data.editItem = row;

      }
    };
    //保存
    const save = async () => {

      if (form.phone && !validatePhoneNumber(form.phone)) {
        tips("联系电话格式不正确！", 'warning');
        return false;
      }
      if(form.unitTypeId=='1'){

        form.contact=form.contactId

      }

      // 内部人员
      if (data.addType == "add") {

        unitList.unshift(JSON.parse(JSON.stringify(form)));

      } else {

        var index = unitList.indexOf(data.editItem);

        console.log(index)

        if (index > -1) {

          unitList[index] = JSON.parse(JSON.stringify(form));

        }
      }

      emit("paramsChange", unitList);

      data.addPeople = false;
      form.unitType = "";
      form.unitTypeId = "0";
      form.unitName = "";
      form.unitId = "";
      form.sort = 1;
      form.contact = "";
      form.contactId = "";
      form.phone = "";
      form.id = new Date().getTime();
    };

    //删除
    const handleDelete = async (row) => {

      Modals('是否删除选择内容', '提示', 'warning').then(async () => {
        var index = unitList.indexOf(row);
          if (index > -1) {
            //大于0 代表存在，
            unitList.splice(index, 1); //存在就删除
          }
          emit("paramsChange", unitList);
        }).catch(() => {
          console.log("点击了取消")
        })
    };

    onMounted(() => {
      affiliation();
    });

    watch(
      () => props.members,
      (newValue, oldValue) => {
        if (props.membersFlag) {
          unitList.length = 0;
          if (newValue.length > 0) {
            newValue.forEach((e) => {
              unitList.unshift(e);
            });
          }
        }
      }

    );

    return {
      data,
      form,
      value,
      unitList,
      handleEdit,
      addPeople,
      close,
      handleDelete,
      save,
      changeValue0,
      changeValue2,
      changeValue7,
      affiliation,
    };
  },
};
</script>

<style scoped lang="scss">
.demo-form-inline .el-form-item {
  width: 70%;
}

.el-select {
  width: 100%;
  margin: 0;
}
</style>
